<template>
  <el-dialog :visible.sync="show" title="故障维修" :close-on-click-modal="false" :append-to-body="true" width='65%' :close-on-press-escape="false" @open="open" @close="close" >
    <div class="worksheet-container failureDetailDialog">
        <div  class="worksheet-detail-container">
          <!-- 工单详情 -->
          <div class="worksheet-detail">
            <div class="worksheet-title">
              <div>故障维修工单号：{{wbOrder.wbOrderCode}}</div>
              <div v-if="status">状态：{{wbOrder.wbOrderStatusName}}</div>
            </div>

            <!-- 上报内容 -->
            <div class="worksheet-info-box">
              <div class="info-title"><i class="el-icon-caret-right"></i>上报内容<span class="time">{{report.createTime}}</span></div>
              <div class="info-row">
                <div class="info-item">
                  <div class="label">所属单位：</div><div class="content text-ellipsis">{{report.deptName}}</div>
                </div>
                <template v-if="report.reportType === 1">
                  <div class="info-item" >
                    <div class="label">设备类型：</div><div class="content">{{report.deviceTypeName}}</div>
                  </div>
                  <div class="info-item">
                    <template v-if="report.reportType === 1">
                      <div class="label">设备状态：</div><div class="content">{{report.deviceStatusName}}</div>
                    </template>
                    <template v-if="report.reportType === 2">
                      <div class="label">设备状态：</div><div class="content">{{report.facilityStatusName}}</div>
                    </template>
                  </div>
                </template>
                <template v-if="report.reportType === 2">
                  <div class="info-item">
                    <div class="label">设施类型：</div><div class="content">{{report.facilityTypeName}}</div>
                  </div>
                  <div class="info-item">
                    <div class="label">处理方式：</div><div class="content">上报工单</div>
                  </div>
                </template>
              </div>
              <div class="info-row">
                <template v-if="report.reportType === 1">
                  <div class="info-item">
                    <div class="label">处理方式：</div><div class="content">上报工单</div>
                  </div>
                  <div class="info-item">
                    <div class="label">上报人：</div><div class="content">{{report.createUserName}}</div>
                  </div>
                  <div class="info-item">
                    <div class="label">联系方式：</div><div class="content">{{report.createUserPhone}}</div>
                  </div>
                </template>
                <template v-if="report.reportType === 2">
                  <div class="info-item">
                    <div class="label">位置描述：</div><div class="content text-ellipsis">{{report.locationDesc}}</div>
                  </div>
                  <div class="info-item">
                    <div class="label">设施编号：</div><div class="content">{{report.facilityNo}}</div>
                  </div>
                  <div class="info-item">
                    <div class="label">上报人：</div><div class="content">{{report.createUserName}}</div>
                  </div>
                </template>
              </div>
              <div class="info-row">
                <div class="info-item long">
                  <div class="label">隐患内容：</div><div class="content infoDiv">{{report.reportContent}}</div>
                </div>
              </div>
              <div class="img-row"  v-if="report.reportImgs">
                <el-image
                  v-for="(img, idx) in report.reportImgs.split(',')"
                  class="img"
                  :key="idx"
                  :src="urlText+'/admin/sys-file/' + img"
                  :alt="img"
                  :preview-src-list="[urlText+'/admin/sys-file/' + img]"
                  :z-index="998"
                ></el-image>
              </div>
              <div class="btn-row">
                <el-button type="primary" size="mini" @click="viewDetail(report)" :disabled="status === 'hasHandle'">{{status === 'hasHandle' ? '订单已完成，无法查看' : '查看详情'}}</el-button>
              </div>
            </div>

            <!-- 指派人员 -->
            <div class="select-user-container dialog-table-container" v-if="status === 'unAssign'">
              <div class="user-action">
                <div class="search-bar">
                  <el-input v-model="userSearch.nameorphone" size="mini" placeholder="输入人员姓名、手机号" clearable/>
                  <el-button type="primary" @click="getUserList" size="mini" style="margin-left: 0.125rem;">查询</el-button>
                </div>
                <el-button type="primary" @click="assign" size="mini">指派</el-button>
              </div>
              <el-table
                ref="userTable"
                class="single"
                size="mini"
                v-loading="useListLoading"
                :data="userList"
                @row-click="rowClick"
                @selection-change="selectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="用户名" prop="username"/>
                <el-table-column label="真实姓名" prop="realName"/>
                <el-table-column label="手机号" prop="phone"/>
                <el-table-column label="角色" prop="roleName"/>
              </el-table>
              <pagination v-show="userPage.total > 0" :total="userPage.total" :page.sync="userPage.currentPage" :limit.sync="userPage.pageSize" @pagination="getUserList"/>
            </div>

            <!-- 处理工单 -->
            <div class="worksheet-info-box" v-if="status === 'waitHandle'" >
              <el-form class="handle-form" ref="handleForm" size="mini" :rules="rules" :model="handleParams" label-width="80px">
                <div class="info-title"><i class="el-icon-caret-right"></i>处理工单</div>
                <div class="info-row">
                  <el-form-item label="处理人员：" style="width: 30%;">
                    <div class="content">{{userInfo.realName}}</div>
                  </el-form-item>
                  <el-form-item label="处理结果：" prop="handleResult" style="width: 30%;">
                    <el-select size="mini" v-model="handleParams.handleResult" clearable placeholder="请选择处理结果">
                      <el-option label="已修复" :value="3"/>
                      <el-option label="未修复" :value="4"/>
                    </el-select>
                  </el-form-item>
                </div>
                <div class="info-row">
                  <el-form-item label="处理内容：" prop="opinion" style="width: 100%;">
                    <el-input type="textarea" size="mini" v-model="handleParams.opinion" placeholder="请输入处理内容" rows="4" maxlength="500" show-word-limit/>
                  </el-form-item>
                </div>
                <div class="btn-row">
                  <el-button :loading="handleFlag" type="primary" @click="handleOrder" size="mini">提交</el-button>
                </div>
              </el-form>
            </div>

            <!-- 审核记录 -->
            <div class="timeline-container" v-if="status === 'waitHandle' || status === 'hasHandle'">
              <div class="timeline-item" v-if="status === 'hasHandle' && auditList.length" style="height: 0.5rem;">
                <div class="item-title">
                  <i class="circle active"></i>
                  <div class="step">完成</div>
                </div>
              </div>
              <template  v-for="(item, index) in auditList">
                <div class="timeline-item" v-if="item.actNodeCode === 'wb_node_02'" :key="index">
                  <div class="item-title">
                    <i class="circle active"></i>
                    <div>处理工单</div>
                    <div class="time">{{item.createTime}}</div>
                  </div>
                  <div class="info-box">
                    <div class="info-row">
                      <div class="info-item">
                        <div class="label">处理人员：</div><div class="content">{{item.auditUserName}}</div>
                      </div>
                      <div class="info-item">
                        <div class="label">联系方式：</div><div class="content">{{item.auditUserPhone}}</div>
                      </div>
                      <div class="info-item">
                        <div class="label">处理结果：</div><div class="content">{{item.handleResultName}}</div>
                      </div>
                    </div>
                    <div class="info-row">
                      <div class="info-item long">
                        <div class="label">处理内容：</div><div class="content infoDiv">{{item.handleOpinion}}</div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="timeline-item" v-if="item.actNodeCode === 'defect_treatment_04'" :key="index">
                  <div class="item-title">
                    <i class="circle active"></i>
                    <div>处理审核</div>
                    <div class="time">{{item.createTime}}</div>
                    <div>{{item.handleResultName}}</div>
                  </div>
                  <div class="info-box">
                    <div class="info-row">
                      <div class="info-item">
                        <div class="label">审核人员：</div><div class="content">{{item.auditUserName}}</div>
                      </div>
                      <div class="info-item">
                        <div class="label">联系方式：</div><div class="content">{{item.auditUserPhone}}</div>
                      </div>
                    </div>
                    <div class="info-row">
                      <div class="info-item long">
                        <div class="label">处理审核：</div><div class="content infoDiv">{{item.handleOpinion}}</div>
                      </div>
                    </div>
                  </div>
                </div>
              </template>
            </div>

          </div>
        </div>
    </div>

    <!-- 隐患详情 -->
    <template v-show="report.reportType === 1">
      <device-alarm-detail  :history="history" :detail="report" :visible.sync="showDetailDialog" />
    </template>
    <template v-show="report.reportType === 2">
      <facilities-failure-detail  :history="history" :detail="report" :visible.sync="showDetailDialog" />
    </template>
  </el-dialog>
</template>

<script>
import Pagination from '../Pagination/index.vue'
import facilitiesFailureDetail from './facilitiesFailureDetail.vue'
import deviceAlarmDetail from './deviceAlarmDetail'
import danger from "@/api/monitor/hiddenDanger.js"

export default {
  name: 'failureDetailDialog',
  components: {
		Pagination,
		facilitiesFailureDetail,
		deviceAlarmDetail,
    },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    status: {
      type: String,
      default: '' // unAssign  waitHandle  hasHandle
    },
    // 功能概览页面维修去处理来的工单号
    WbOrderCodeId: {
      type: String,
      default: '' // unAssign  waitHandle  hasHandle
    },
    detail: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      orderList: [], // 维保子单列表
      orderSearch: {
        wbOrderCode: ''
      },
      currentOrder: {},
      orderPage: {
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      orderLoading: false,
      userList: [],
      userSearch: {
        nameorphone: ''
      },
      userPage: {
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      useListLoading: false,
      userSelected: [],
      assignParams: {}, // 指派人员数据
      handleParams: {
        handleResult: 3,
        opinion:''
      },
      auditList: [], // 审核记录
      wbOrder: {}, // 维保子工单
      report: {}, // 上报工单
      statusMap: {
        'unAssign': {
          text: '未指派',
          handle:danger.getUnAssignHandleOrder,
        },
        'waitHandle': {
          text: '待处理',
          handle:danger.getWaitHandleOrder,
        },
        'hasHandle': {
          text: '已处理',
          handle:danger.getHasHandleOrder,
        }
      },
      rules: {
        handleResult: [{required: true, message: '请选择处理结果', trigger: 'change'}],
        opinion:  [{required: true, message: '请输入处理内容', trigger: 'blur'}],
      },
      history: [], // 隐患详情里的审核记录
      actualData: {
        deviceId: 0,
        deviceCode: '',
        deptId: 0,
      },
      showDetailDialog: false, // 隐患详情
      showActualData: false, // 设备实时数据
      showInspectDialog: false, // 设施巡查
      inspectFlag:false,//判断是否有巡查记录

      inspectionFlag:false,
      inspectId:'',
      deptNewId:'',

      handleFlag:false,
      userInfo:'',
      userDept:'',
      urlText:uni.getStorageSync('urlText')
    }
  },
   async created(){
			this. userInfoGet()
        },
  computed: {
    show: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
  },
  methods: {
     userInfoGet(){
        this.userInfo=JSON.parse(uni.getStorageSync('user'))
        this.userDept=uni.getStorageSync('userDept')
		},
    // 打开弹框
    open() {
      this.getOrderList()
    },
    // 功能概览页面维修去处理来的工单号
    openDetailDialogOne(wbOrderCode) {
      this.orderSearch.wbOrderCode = wbOrderCode
      this.getOrderList()
    },
    // 获取工单列表
    getOrderList() {
      const handle = this.statusMap[this.status].handle
      this.orderLoading = true
     handle(Object.assign({
        deptId: this.detail.deptId,
        wbDeptId: this.detail.wbDeptId,
        pageNum: this.orderPage.currentPage,
        pageSize: this.orderPage.pageSize
      }, this.orderSearch)).then(res => {
        this.orderList = res.data.list
        this.orderPage.total = res.data.total
        this.orderLoading = false
        if (this.orderList.length) {
          this.getOrderDetail(this.orderList[0])
          // 未指派状态请求维保人员列表
          if (this.status === 'unAssign') {
            this.getUserList()
          }
        } else {
          this.auditList = {}
          this.wbOrder = {}
          this.report = {}
          this.userList = []
        }
      }).catch(() => {this.orderLoading = false})
    },
    // 获取工单详情
	async getOrderDetail(row) {
		this.currentOrder = row
		// 获取工单详情
		let res=await danger.getWbAuditDetails({wbOrderId: row.wbOrderId})

        const {auditList, wbOrder, report} = res.data

        this.auditList = auditList
        console.log( this.auditList,' this.auditList ' );
        this.wbOrder = wbOrder
        this.report = report

    },
    // 查询维保人员列表
    getUserList() {
      this.useListLoading = true
     danger.getWbUsers(Object.assign({
        pageNum: this.userPage.currentPage,
        pageSize: this.userPage.pageSize,
        deptId: this.detail.wbDeptId
      }, this.userSearch)).then(res => {
        this.userList = res.data.list
        this.userPage.total = res.data.total
        this.useListLoading = false
      }).catch(() => this.useListLoading = false)
    },
    // 点击表格
    rowClick(row) {
      this.$refs['userTable'].toggleRowSelection(row)
    },
    // 监听表格选项变化
    selectionChange(val) {
      if (val.length > 1) {
        const row = val.pop()
        this.$refs['userTable'].clearSelection()
        this.$refs['userTable'].toggleRowSelection(row)
      } else {
        this.userSelected = val
      }
    },
    // 指派人员提交
    assign() {
      if (!this.userSelected.length) {
        return this.$message.warning('请选择要指派的人员！')
      }
      danger.doWbUserAssign({
        wbOrderId: this.wbOrder.id,
        wbUserId: this.userSelected[0].userId
      }).then(res => {
        if (res.code === 0) {
          this.$message.success('操作成功！')
          this.getOrderList()
          this.$emit('success')
        } else {
          this.$message.error(res.msg)
        }
      }).catch(() => {})
    },
    // 处理工单提交
    handleOrder() {
      this.handleFlag=true
      this.handleParams.wbOrderId = this.wbOrder.id

      this.$refs['handleForm'].validate((valid) => {
        if (valid) {
         danger.doHandleWbOrder(this.handleParams).then(res => {
          if(res.code==1){

            this.$message.error(res.msg)
            this.handleFlag=false

          }else{
             this.$message.success('操作成功！')

             this.show=false
            if(this.status=='waitHandle'){
              this.handleParams.opinion = ''
              this.getOrderList()
            }
             this.handleFlag=false
             this.$emit('success')
          }


          }).catch(() => this.handleFlag=false)
        }else{
          this.handleFlag=false
        }
      })

    },
    close() {
      this.handleParams.opinion = ''
      this.orderSearch.wbOrderCode = ''
      this.userSearch.nameorphone = ''
    },
    // 故障单详情
    viewDetail(report) {
     danger. getAuditDetails({id: report.id}).then(res => {
        if (res.code === 0) {
          this.history = res.data
        } else {
          this.$message.error(res.msg)
        }
      })
      this.showDetailDialog = true
    },
    // 设备实时数据
    viewDevice(report) {
      this.actualData.deviceCode = report.deviceCode
      this.actualData.deviceId = report.deviceId
      this.actualData.deptId = report.deptId
      this.showActualData = true
    },
    // 设施巡查记录
    viewFacility(report) {
      danger.getInspectHisPagedList({deptId: this.detail.deptId,facilityNo: report.facilityNo}).then(res => {
        console.log(res)
        if (res.code === 0) {
          if(res.data.list.length){
            danger.getInspectDetail({
              deptId: this.detail.deptId,
              id:res.data.list[0].id
            })
              .then((resNew) => {
                console.log(resNew)
                if(resNew.data){
                  this.inspectId=res.data.list[0].id
                  this.inspectionFlag = true
                }else{
                  this.$message.warning('暂无巡检记录')
                }
              })

          }else{
            this.$message.warning('暂无巡检记录')
          }
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
  }
}
</script>
<style lang="scss" scoped>
.info-item{
  .label{
   color: #B8BDC1 ;
  }
}

</style>

<style lang='scss'>
.worksheet-container {
  // width: 100%;
  // min-width: 17.5rem;
  // margin: 0 auto;
  color: #fff;
  .worksheet-list-container {
    position: absolute;
    .search-worksheet {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 0.25rem;
    }
    .worksheet-list {
      display: flex;
      flex-direction: column;
      height: calc(100vh - 2.625rem);
      overflow: auto;
      .worksheet-item {
        display: flex;
        flex-direction: column;
        padding: 0.25rem;
        margin: 0 0.05rem 0.25rem 0;
        // border:0.0125rem solid rgba(74,74,74,0.5);

        cursor: pointer;
        transition: all linear 0.3s;
        //&.active {
        //  //border:0.0125rem solid rgba(70,178,160,1);
        //}
        &:last-child {
          margin-bottom: 0;
        }
        .info-row {
          display: flex;
          line-height: 0.35rem;
          .label {
            width: 1rem;
          }
          .content {
            flex: 1;
            color: rgba(255, 255, 255,0.9);
          }
        }
      }
    }
  }
  .worksheet-detail-container {
    // position: absolute;
    // right: 0;
    // height: calc(100vh - 1.25rem);
    // overflow: auto;
    .worksheet-detail {
      display: flex;
      flex-direction: column;
      flex: 1;
      // border:0.0125rem solid rgba(74,74,74,0.5);
      .worksheet-title {
        display: flex;
        justify-content: space-between;
        padding: 0.25rem 0.375rem;
        font-size: 0.2rem;
        line-height: 0.35rem;
        border-bottom: 0.0125rem solid rgba(2, 195, 255, 0.1);
        color: rgba(2, 195, 255, 1);
      }
      .worksheet-info-box {
        padding: 0.25rem 0;
        border-bottom: 0.0125rem solid rgba(2, 195, 255, 0.1);
        .info-title {
          font-size: 0.2rem;
          color: rgba(2, 195, 255, 1);
          .time {
            margin-left: 0.375rem;
            font-size: 0.175rem;
            color: rgba(2, 195, 255, 0.6);
          }
        }
        .info-row {
          display: flex;
          justify-content: space-between;
          margin: 0.125rem 0 0.125rem 0.25rem;
          .info-item {
            display: flex;
            font-size: 0.175rem;
            line-height: 0.35rem;
            width: 32%;
            .label {
              width: 1.125rem;
              color: #B8BDC1;
            }
            .content {
              flex: 1;
              color:  rgba(255, 255, 255,0.9);
            }
            &.long {
              width: 100%;
            }
          }
        }
        .btn-row {
          text-align: right;
        }
        .img-row {
          display: flex;
          flex-wrap: wrap;
          margin: 0.125rem 0 0.125rem 0.25rem;
          .img {
            width: 20%;
            height: 1.5rem;
            margin: 0 0.125rem 0.125rem 0;
          }
        }
        .handle-form {
          .info-row {
            display: flex;
            justify-content: flex-start;
            margin: 0.125rem 0 0.125rem 0.25rem;
            .el-form-item__label {
              color: rgba(2, 195, 255, 1);
            }
          }
        }
      }
      .timeline-container {
        width:95%;

      }
      .select-user-container {
        padding: 0.25rem;
        .user-action {
          display: flex;
          justify-content: space-between;
          margin-bottom: 0.25rem;
          .search-bar {
            display: flex;
          }
        }
      }
    }
  }

}
</style>
